package com.netpace.iem.umair.dal;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.netpace.iem.umair.model.Unit;

public class UnitMemory implements IUnitDao {
	private List<Unit> units;
	Connection conn;
	static Logger log = Logger.getLogger(CategoryMemory.class.getName());

	// Default constructor is for Main memory Db
	public UnitMemory() {
		this.units = new ArrayList<Unit>();
	}
	
	@Override
	public void insert(Unit unit){
		log.debug("1 record inserted");
		units.add(unit);
	}
	
	@Override
	public void update(Unit unit, int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			log.debug("1 record updated");
			units.remove(index);
			units.add(index, unit);
		}
	}
	
	@Override
	public void delete(Unit unit, int pk) {
		int index = getIndex(unit); 
		if ( index != -1 ) {
			log.debug("1 record deleted");
			units.remove(index);
		}
	}
	
	@Override
	public void delete(int pk) {
		int index = getIndex(pk); 
		if ( index != -1 ) {
			log.debug("1 record deleted");
			units.remove(index);
		}
	}
	
	@Override
	public Unit findById(int pk) {
		int index = getIndex(pk); 
		
		if ( index != -1 ) {
			log.debug("returning the record found");
			return units.get(index);
		}
		
		return null;
	}
	
	@Override
	public List<Unit> findAll(){
		log.debug("returning the records found");
		return units;
	}
	
	private int getIndex(Unit unit) {
		if ( units.contains(unit) ) 
			return units.indexOf(unit);
		else
			return -1;
	}
	
	private int getIndex(int pk) {
		for (int i = 0; i < units.size(); i++) {
			if ( units.get(i).getId() == pk ) {
				return i;
			}
		}
		
		return -1;
	}

}
